package utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;

import core.rendering.Renderable;

/**
 * This FPSWidget allows us to place a FPS calculator on screen. It can be added
 * as a renderable.
 * 
 * @author Norvin Altamirano Ruiz
 * 
 */
public class FPSWidget extends Renderable {

	private long time;
	private long timeb;
	private int cumfps = 0;
	private long fps = 0;
	Paint p;
	long fpsecs;
	long sum;
	long fpsm = 0;
	long timebm = 0;
	boolean enabled = true;

	public FPSWidget() {
		super(10, 10);
		timeb = System.nanoTime();
		time = System.nanoTime();
	}

	/**
	 * Renders the element and send a tick for FPS calculation.
	 */
	@Override
	public void renderComponent(Graphics2D g2d) {
		if (enabled) {
			
			g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
			g2d.setColor(Color.DARK_GRAY);
			g2d.fillRect((int) getX(), (int) getY(), 90, 30);
			g2d.setColor(Color.GREEN);
			g2d.drawString("FPS: " + fps, (int) getX() + 20, getY() + 20);
			g2d.setColor(Color.DARK_GRAY);
			g2d.fillRect((int) getX(), (int) getY() + 30, 90, 30);
			g2d.setColor(Color.RED);
			g2d.drawString("FPSM: " + fpsm, getX() + 25, getY() + 45);
		}
		tick();

	}

	/**
	 * Ticks the current frame.
	 */
	public void tick() {
		cumfps++;
		time = System.nanoTime();

		fps = 1000000000 / (time - timeb);
		timeb = time;

		sum += fps;
		fpsecs++;
		if (2000000000 < time - timebm) {
			fpsm = sum / fpsecs;
			fpsecs = 0;
			sum = 0;
			timebm = time;
		}
	}

	@Override
	public void updateLogic() {
		// TODO Auto-generated method stub

	}

}
